<template>
  <div class="register-form-component">
    <div class="register-form-wrapper">
      <!-- 表单标题区域 -->
      <div v-if="showHeader" class="header-section text-center mb-8">
        <h2 class="section-title">{{ title }}</h2>
        <p class="section-subtitle">{{ subtitle }}</p>
      </div>
      
      <!-- 注册表单 -->
      <form @submit.prevent="handleSubmit" class="register-form" novalidate>
        <!-- 用户名 -->
        <div class="form-group mb-5">
          <label
            :for="`${idPrefix}-username`"
            class="form-label block mb-2"
          >
            {{ fields.username.label }}
            <span v-if="fields.username.required" class="text-red-500"> *</span>
          </label>
          <input
            :id="`${idPrefix}-username`"
            type="text"
            v-model="formData.username"
            :placeholder="fields.username.placeholder"
            class="form-input"
            :class="{ 'error': errors.username }"
            :disabled="isSubmitting"
            :required="fields.username.required"
          >
          <p v-if="errors.username" class="error-message">{{ errors.username }}</p>
        </div>
        
        <!-- 邮箱 -->
        <div class="form-group mb-5">
          <label
            :for="`${idPrefix}-email`"
            class="form-label block mb-2"
          >
            {{ fields.email.label }}
            <span v-if="fields.email.required" class="text-red-500"> *</span>
          </label>
          <input
            :id="`${idPrefix}-email`"
            type="email"
            v-model="formData.email"
            :placeholder="fields.email.placeholder"
            class="form-input"
            :class="{ 'error': errors.email }"
            :disabled="isSubmitting"
            :required="fields.email.required"
          >
          <p v-if="errors.email" class="error-message">{{ errors.email }}</p>
        </div>
        
        <!-- 手机号 -->
        <div v-if="showPhoneField" class="form-group mb-5">
          <label
            :for="`${idPrefix}-phone`"
            class="form-label block mb-2"
          >
            {{ fields.phone.label }}
            <span v-if="fields.phone.required" class="text-red-500"> *</span>
          </label>
          <input
            :id="`${idPrefix}-phone`"
            type="tel"
            v-model="formData.phone"
            :placeholder="fields.phone.placeholder"
            class="form-input"
            :class="{ 'error': errors.phone }"
            :disabled="isSubmitting"
            :required="fields.phone.required"
          >
          <p v-if="errors.phone" class="error-message">{{ errors.phone }}</p>
        </div>
        
        <!-- 验证码 -->
        <div v-if="showVerificationCode" class="form-group mb-5">
          <label
            :for="`${idPrefix}-verification-code`"
            class="form-label block mb-2"
          >
            {{ fields.verificationCode.label }}
            <span v-if="fields.verificationCode.required" class="text-red-500"> *</span>
          </label>
          <div class="flex space-x-3">
            <input
              :id="`${idPrefix}-verification-code`"
              type="text"
              v-model="formData.verificationCode"
              :placeholder="fields.verificationCode.placeholder"
              class="form-input flex-1"
              :class="{ 'error': errors.verificationCode }"
              :disabled="isSubmitting || isSendingCode"
              :required="fields.verificationCode.required"
            >
            <button
              type="button"
              class="code-button"
              :class="{ 'disabled': isSubmitting || isSendingCode || countdown > 0 }"
              :disabled="isSubmitting || isSendingCode || countdown > 0"
              @click="sendVerificationCode"
            >
              <span v-if="!isSendingCode">{{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}</span>
              <span v-if="isSendingCode"><i class="fa fa-spinner fa-spin mr-1"></i>发送中</span>
            </button>
          </div>
          <p v-if="errors.verificationCode" class="error-message">{{ errors.verificationCode }}</p>
        </div>
        
        <!-- 密码 -->
        <div class="form-group mb-5">
          <label
            :for="`${idPrefix}-password`"
            class="form-label block mb-2"
          >
            {{ fields.password.label }}
            <span v-if="fields.password.required" class="text-red-500"> *</span>
          </label>
          <div class="relative">
            <input
              :id="`${idPrefix}-password`"
              :type="showPassword ? 'text' : 'password'"
              v-model="formData.password"
              :placeholder="fields.password.placeholder"
              class="form-input"
              :class="{ 'error': errors.password }"
              :disabled="isSubmitting"
              :required="fields.password.required"
            >
            <button
              type="button"
              class="toggle-password"
              @click="toggleShowPassword"
              :disabled="isSubmitting"
            >
              <i class="fa" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
            </button>
          </div>
          <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
        </div>
        
        <!-- 确认密码 -->
        <div class="form-group mb-6">
          <label
            :for="`${idPrefix}-confirmPassword`"
            class="form-label block mb-2"
          >
            {{ fields.confirmPassword.label }}
            <span v-if="fields.confirmPassword.required" class="text-red-500"> *</span>
          </label>
          <div class="relative">
            <input
              :id="`${idPrefix}-confirmPassword`"
              :type="showPassword ? 'text' : 'password'"
              v-model="formData.confirmPassword"
              :placeholder="fields.confirmPassword.placeholder"
              class="form-input"
              :class="{ 'error': errors.confirmPassword }"
              :disabled="isSubmitting"
              :required="fields.confirmPassword.required"
            >
          </div>
          <p v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</p>
        </div>
        
        <!-- 用户协议 -->
        <div v-if="showTermsCheckbox" class="form-group mb-6">
          <label class="flex items-start">
            <input
              type="checkbox"
              v-model="formData.acceptTerms"
              class="terms-checkbox"
              :class="{ 'error': errors.acceptTerms }"
              :disabled="isSubmitting"
              :required="fields.acceptTerms.required"
            >
            <span class="ml-2 text-sm">
              我已阅读并同意
              <a href="#" class="primary-link" @click.prevent="handleTermsClick">《用户协议》</a>
              和
              <a href="#" class="primary-link" @click.prevent="handlePrivacyClick">《隐私政策》</a>
            </span>
          </label>
          <p v-if="errors.acceptTerms" class="error-message">{{ errors.acceptTerms }}</p>
        </div>
        
        <!-- 注册按钮 -->
        <button
          type="submit"
          class="submit-button"
          :disabled="isSubmitting"
        >
          <span v-if="!isSubmitting">{{ submitButtonText }}</span>
          <span v-if="isSubmitting" class="flex items-center">
            <i class="fa fa-spinner fa-spin mr-2"></i>注册中...
          </span>
        </button>
        
        <!-- 其他注册方式 -->
        <div class="text-center mt-6" v-if="socialRegisterOptions.length > 0">
          <p class="mb-4">或通过以下方式注册</p>
          
          <div class="flex justify-center space-x-4">
            <a
              href="#"
              v-for="(option, index) in socialRegisterOptions"
              :key="index"
              class="social-button"
              :class="`social-${option.provider}`"
              @click.prevent="handleSocialRegister(option.provider)"
              :disabled="isSubmitting"
              :title="option.label"
            >
              <i :class="`fa ${option.icon} text-xl`"></i>
            </a>
          </div>
        </div>
        
        <!-- 登录入口 -->
        <p class="text-center mt-6" v-if="showLoginLink">
          已有账号？
          <a href="#" class="primary-link font-medium" @click.prevent="handleLoginClick">
            立即登录
          </a>
        </p>
        
        <!-- 注册状态提示 -->
        <div v-if="registerStatus === 'success'" class="status-message success">
          注册成功，正在跳转...
        </div>
        <div v-else-if="registerStatus === 'error'" class="status-message error">
          {{ errorMessage }}
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterForm',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'register-form',
      displayName: '用户注册表单',
      description: '完整的用户注册表单组件，支持多种字段配置和第三方登录',
      icon: 'fa-user-plus',
      category: '用户组件',
      version: '1.0.0',
      isContainer: false,
    },
    
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'title',
            label: '主标题',
            type: 'text',
            defaultValue: '创建新账户'
          },
          {
            name: 'subtitle',
            label: '副标题',
            type: 'text',
            defaultValue: '加入我们，享受更多优质服务'
          },
          {
            name: 'backgroundType',
            label: '背景类型',
            type: 'select',
            options: [
              { label: '纯色', value: 'solid' },
              { label: '渐变色', value: 'gradient' }
            ],
            defaultValue: 'gradient'
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#ffffff'
          },
          {
            name: 'bgColor2',
            label: '渐变背景色2',
            type: 'color',
            defaultValue: '#f0f7ff'
          },
          {
            name: 'showHeader',
            label: '显示标题区域',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {
        title: '表单配置',
        fields: [
          {
            name: 'formRadius',
            label: '表单圆角',
            type: 'number',
            min: 0,
            max: 30,
            defaultValue: 12
          },
          {
            name: 'idPrefix',
            label: 'ID前缀',
            type: 'text',
            defaultValue: 'register',
            description: '用于表单元素ID的前缀，避免重复'
          },
          {
            name: 'showPhoneField',
            label: '显示手机号字段',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'showVerificationCode',
            label: '显示验证码',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'verificationEndpoint',
            label: '验证码接口',
            type: 'text',
            defaultValue: '/api/send-verification-code'
          },
          {
            name: 'registerEndpoint',
            label: '注册接口',
            type: 'text',
            defaultValue: '/api/register'
          },
          {
            name: 'showTermsCheckbox',
            label: '显示用户协议复选框',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'showLoginLink',
            label: '显示登录链接',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'submitButtonText',
            label: '提交按钮文本',
            type: 'text',
            defaultValue: '立即注册'
          }
        ]
      },
      {
        title: '字段配置',
        fields: [
          {
            name: 'fields',
            label: '字段设置',
            type: 'object',
            properties: [
              {
                name: 'username',
                label: '用户名字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '用户名' },
                  { name: 'placeholder', type: 'text', defaultValue: '请输入用户名' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'email',
                label: '邮箱字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '邮箱' },
                  { name: 'placeholder', type: 'text', defaultValue: '请输入邮箱地址' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'phone',
                label: '手机号字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '手机号' },
                  { name: 'placeholder', type: 'text', defaultValue: '请输入手机号' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'verificationCode',
                label: '验证码字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '验证码' },
                  { name: 'placeholder', type: 'text', defaultValue: '请输入验证码' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'password',
                label: '密码字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '密码' },
                  { name: 'placeholder', type: 'text', defaultValue: '请设置密码' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'confirmPassword',
                label: '确认密码字段',
                type: 'object',
                properties: [
                  { name: 'label', type: 'text', defaultValue: '确认密码' },
                  { name: 'placeholder', type: 'text', defaultValue: '请再次输入密码' },
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              },
              {
                name: 'acceptTerms',
                label: '用户协议字段',
                type: 'object',
                properties: [
                  { name: 'required', type: 'boolean', defaultValue: true }
                ]
              }
            ]
          }
        ]
      },
      {
        title: '第三方登录配置',
        fields: [
          {
            name: 'socialRegisterOptions',
            label: '第三方注册选项',
            type: 'array',
            defaultValue: [
              { label: '微信', value: 'wechat', provider: 'wechat', icon: 'fa-weixin' },
              { label: 'QQ', value: 'qq', provider: 'qq', icon: 'fa-qq' },
              { label: 'GitHub', value: 'github', provider: 'github', icon: 'fa-github' }
            ]
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'registerSubmit',
        label: '表单提交',
        description: '当注册表单提交时触发',
        parameters: [
          { name: 'data', type: 'object', description: '表单数据' },
          { name: 'timestamp', type: 'number', description: '提交时间戳' }
        ]
      },
      {
        name: 'registerSuccess',
        label: '注册成功',
        description: '当注册成功时触发',
        parameters: [
          { name: 'response', type: 'object', description: '服务器响应' },
          { name: 'data', type: 'object', description: '提交的表单数据' }
        ]
      },
      {
        name: 'registerError',
        label: '注册失败',
        description: '当注册失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' },
          { name: 'data', type: 'object', description: '提交的表单数据' }
        ]
      },
      {
        name: 'sendVerificationCode',
        label: '发送验证码',
        description: '当发送验证码时触发',
        parameters: [
          { name: 'contact', type: 'string', description: '邮箱或手机号' }
        ]
      },
      {
        name: 'verificationCodeSent',
        label: '验证码发送成功',
        description: '当验证码发送成功时触发',
        parameters: [
          { name: 'response', type: 'object', description: '服务器响应' },
          { name: 'contact', type: 'string', description: '邮箱或手机号' }
        ]
      },
      {
        name: 'login',
        label: '跳转登录',
        description: '当点击登录链接时触发'
      },
      {
        name: 'socialRegister',
        label: '第三方注册',
        description: '当点击第三方注册时触发',
        parameters: [
          { name: 'provider', type: 'string', description: '第三方平台' }
        ]
      },
      {
        name: 'termsClick',
        label: '用户协议点击',
        description: '当点击用户协议链接时触发'
      },
      {
        name: 'privacyClick',
        label: '隐私政策点击',
        description: '当点击隐私政策链接时触发'
      }
    ],
    
    methods: [
      {
        name: 'resetForm',
        label: '重置表单',
        description: '清空注册表单内容'
      },
      {
        name: 'setFormData',
        label: '设置表单数据',
        description: '设置注册表单字段值',
        parameters: [
          { name: 'data', type: 'object', required: true, description: '表单数据对象' }
        ]
      },
      {
        name: 'submitForm',
        label: '提交表单',
        description: '手动触发表单提交'
      },
      {
        name: 'sendVerificationCode',
        label: '发送验证码',
        description: '手动发送验证码'
      }
    ]
  },
  
  props: {
    // 基本配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    title: {
      type: String,
      default: '创建新账户'
    },
    subtitle: {
      type: String,
      default: '加入我们，享受更多优质服务'
    },
    
    children: {
      type: Array,
      default: () => []
    },
    // 背景配置
    backgroundType: {
      type: String,
      default: 'gradient',
      validator: (value) => ['solid', 'gradient'].includes(value)
    },
    bgColor: {
      type: String,
      default: '#ffffff'
    },
    bgColor2: {
      type: String,
      default: '#f0f7ff'
    },
    
    // 颜色配置
    titleColor: {
      type: String,
      default: '#1f2937'
    },
    subtitleColor: {
      type: String,
      default: '#6b7280'
    },
    labelColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.8)'
    },
    
    // 表单配置
    formRadius: {
      type: Number,
      default: 12,
      validator: (value) => value >= 0 && value <= 30
    },
    idPrefix: {
      type: String,
      default: 'register'
    },
    showPhoneField: {
      type: Boolean,
      default: true
    },
    showVerificationCode: {
      type: Boolean,
      default: true
    },
    verificationEndpoint: {
      type: String,
      default: '/api/send-verification-code'
    },
    registerEndpoint: {
      type: String,
      default: '/api/register'
    },
    showTermsCheckbox: {
      type: Boolean,
      default: true
    },
    showLoginLink: {
      type: Boolean,
      default: true
    },
    submitButtonText: {
      type: String,
      default: '立即注册'
    },
    
    // 字段配置
    fields: {
      type: Object,
      default: () => ({
        username: {
          label: '用户名',
          placeholder: '请输入用户名',
          required: true
        },
        email: {
          label: '邮箱',
          placeholder: '请输入邮箱地址',
          required: true
        },
        phone: {
          label: '手机号',
          placeholder: '请输入手机号',
          required: true
        },
        verificationCode: {
          label: '验证码',
          placeholder: '请输入验证码',
          required: true
        },
        password: {
          label: '密码',
          placeholder: '请设置密码',
          required: true
        },
        confirmPassword: {
          label: '确认密码',
          placeholder: '请再次输入密码',
          required: true
        },
        acceptTerms: {
          required: true
        }
      })
    },
    
    // 第三方登录配置
    socialRegisterOptions: {
      type: Array,
      default: () => [
        { label: '微信', value: 'wechat', provider: 'wechat', icon: 'fa-weixin' },
        { label: 'QQ', value: 'qq', provider: 'qq', icon: 'fa-qq' },
        { label: 'GitHub', value: 'github', provider: 'github', icon: 'fa-github' }
      ]
    },
    
    // 是否显示标题
    showHeader: {
      type: Boolean,
      default: true
    }
  },
  
  emits: ['registerSubmit', 'registerSuccess', 'registerError', 'sendVerificationCode', 'verificationCodeSent', 'login', 'socialRegister', 'termsClick', 'privacyClick'],
  
  data() {
    return {
      // 表单数据
      formData: {
        username: '',
        email: '',
        phone: '',
        verificationCode: '',
        password: '',
        confirmPassword: '',
        acceptTerms: false
      },
      // 表单状态
      isSubmitting: false,
      registerStatus: null, // null, 'success', 'error'
      errorMessage: '',
      successMessage: '',
      // 密码显示切换
      showPassword: false,
      // 验证码相关
      isSendingCode: false,
      countdown: 0,
      countdownTimer: null,
      // 表单验证错误
      errors: {}
    };
  },
  
  watch: {
    // 监听密码变化，清除确认密码的错误
    'formData.password'() {
      if (this.errors.confirmPassword) {
        delete this.errors.confirmPassword;
      }
    }
  },
  
  beforeUnmount() {
    // 清除计时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
  
  methods: {
    /**
     * 验证表单
     */
    validateForm() {
      const errors = {};
      
      // 验证用户名
      if (this.fields.username.required && !this.formData.username.trim()) {
        errors.username = '请输入用户名';
      } else if (this.formData.username && (this.formData.username.length < 2 || this.formData.username.length > 20)) {
        errors.username = '用户名长度应为2-20个字符';
      }
      
      // 验证邮箱
      if (this.fields.email.required && !this.formData.email.trim()) {
        errors.email = '请输入邮箱地址';
      } else if (this.formData.email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(this.formData.email)) {
          errors.email = '请输入有效的邮箱地址';
        }
      }
      
      // 验证手机号
      if (this.showPhoneField) {
        if (this.fields.phone.required && !this.formData.phone.trim()) {
          errors.phone = '请输入手机号';
        } else if (this.formData.phone) {
          const phoneRegex = /^1[3-9]\d{9}$/;
          if (!phoneRegex.test(this.formData.phone)) {
            errors.phone = '请输入有效的手机号';
          }
        }
      }
      
      // 验证验证码
      if (this.showVerificationCode) {
        if (this.fields.verificationCode.required && !this.formData.verificationCode.trim()) {
          errors.verificationCode = '请输入验证码';
        } else if (this.formData.verificationCode && this.formData.verificationCode.length !== 6) {
          errors.verificationCode = '验证码长度应为6位';
        }
      }
      
      // 验证密码
      if (this.fields.password.required && !this.formData.password) {
        errors.password = '请设置密码';
      } else if (this.formData.password) {
        if (this.formData.password.length < 8 || this.formData.password.length > 20) {
          errors.password = '密码长度应为8-20个字符';
        } else if (!/(?=.*[A-Za-z])(?=.*\d)/.test(this.formData.password)) {
          errors.password = '密码至少包含字母和数字';
        }
      }
      
      // 验证确认密码
      if (this.fields.confirmPassword.required && !this.formData.confirmPassword) {
        errors.confirmPassword = '请确认密码';
      } else if (this.formData.confirmPassword !== this.formData.password) {
        errors.confirmPassword = '两次输入的密码不一致';
      }
      
      // 验证用户协议
      if (this.showTermsCheckbox && this.fields.acceptTerms.required && !this.formData.acceptTerms) {
        errors.acceptTerms = '请阅读并同意用户协议和隐私政策';
      }
      
      this.errors = errors;
      return Object.keys(errors).length === 0;
    },
    
    /**
     * 清除错误
     */
    clearErrors() {
      this.errors = {};
      this.registerStatus = null;
      this.errorMessage = '';
      this.successMessage = '';
    },
    
    /**
     * 切换密码显示
     */
    toggleShowPassword() {
      this.showPassword = !this.showPassword;
    },
    
    /**
     * 发送验证码
     */
    async sendVerificationCode() {
      // 验证邮箱或手机号
      let contact = '';
      
      if (this.showPhoneField && this.formData.phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(this.formData.phone)) {
          this.errors.phone = '请输入有效的手机号';
          return;
        }
        contact = this.formData.phone;
      } else if (this.formData.email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(this.formData.email)) {
          this.errors.email = '请输入有效的邮箱地址';
          return;
        }
        contact = this.formData.email;
      } else {
        if (this.showPhoneField) {
          this.errors.phone = '请输入手机号';
        } else {
          this.errors.email = '请输入邮箱地址';
        }
        return;
      }
      
      // 清除可能存在的错误
      if (this.errors.verificationCode) {
        delete this.errors.verificationCode;
      }
      
      this.isSendingCode = true;
      
      try {
        // 触发发送验证码事件
        this.$emit('sendVerificationCode', contact);
        
        // 模拟API调用
        if (this.verificationEndpoint) {
          // 实际项目中这里会调用真实的API
          await new Promise(resolve => setTimeout(resolve, 1500));
        }
        
        // 触发发送成功事件
        this.$emit('verificationCodeSent', { response: { success: true }, contact });
        
        // 开始倒计时
        this.startCountdown();
      } catch (error) {
        console.error('发送验证码失败:', error);
      } finally {
        this.isSendingCode = false;
      }
    },
    
    /**
     * 开始倒计时
     */
    startCountdown() {
      this.countdown = 60;
      
      // 清除之前的计时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      
      // 设置新的计时器
      this.countdownTimer = setInterval(() => {
        this.countdown--;
        
        if (this.countdown <= 0) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
        }
      }, 1000);
    },
    
    /**
     * 处理表单提交
     */
    async handleSubmit() {
      // 清除之前的错误和状态
      this.clearErrors();
      
      // 验证表单
      if (!this.validateForm()) {
        return;
      }
      
      this.isSubmitting = true;
      
      // 准备提交数据
      const submitData = {
        username: this.formData.username,
        email: this.formData.email,
        password: this.formData.password,
        timestamp: Date.now()
      };
      
      // 如果显示手机号字段，则添加手机号
      if (this.showPhoneField) {
        submitData.phone = this.formData.phone;
      }
      
      // 如果显示验证码字段，则添加验证码
      if (this.showVerificationCode) {
        submitData.verificationCode = this.formData.verificationCode;
      }
      
      // 触发提交事件
      this.$emit('registerSubmit', submitData);
      
      try {
        // 模拟API调用
        if (this.registerEndpoint) {
          // 实际项目中这里会调用真实的API
          await new Promise(resolve => setTimeout(resolve, 2000));
          
          // 模拟成功响应
          const response = {
            success: true,
            message: '注册成功，正在跳转...'
          };
          
          this.registerStatus = 'success';
          this.successMessage = response.message;
          
          // 触发成功事件
          this.$emit('registerSuccess', { response, data: submitData });
          
          // 重置表单
          setTimeout(() => {
            this.resetForm();
          }, 3000);
        } else {
          // 如果没有配置接口，直接触发成功事件
          this.registerStatus = 'success';
          this.successMessage = '注册成功，正在跳转...';
          
          this.$emit('registerSuccess', { 
            response: { success: true, message: '注册成功（模拟）' }, 
            data: submitData 
          });
          
          // 重置表单
          setTimeout(() => {
            this.resetForm();
          }, 3000);
        }
      } catch (error) {
        console.error('注册失败:', error);
        
        this.registerStatus = 'error';
        this.errorMessage = `注册失败: ${error.message || '未知错误'}`;
        
        // 触发错误事件
        this.$emit('registerError', { error, data: submitData });
      } finally {
        this.isSubmitting = false;
      }
    },
    
    /**
     * 处理登录点击
     */
    handleLoginClick() {
      this.$emit('login');
    },
    
    /**
     * 处理第三方注册
     */
    handleSocialRegister(provider) {
      this.$emit('socialRegister', provider);
      // 实际项目中这里会调用对应第三方平台的注册SDK
    },
    
    /**
     * 处理用户协议点击
     */
    handleTermsClick() {
      this.$emit('termsClick');
    },
    
    /**
     * 处理隐私政策点击
     */
    handlePrivacyClick() {
      this.$emit('privacyClick');
    },
    
    /**
     * 重置表单
     */
    resetForm() {
      this.formData = {
        username: '',
        email: '',
        phone: '',
        verificationCode: '',
        password: '',
        confirmPassword: '',
        acceptTerms: false
      };
      
      this.showPassword = false;
      this.clearErrors();
    },
    
    /**
     * 设置表单数据
     */
    setFormData(data) {
      if (typeof data === 'object' && data !== null) {
        this.formData = {
          ...this.formData,
          ...data
        };
        
        this.clearErrors();
      }
    },
    
    /**
     * 手动提交表单
     */
    submitForm() {
      // 触发表单提交
      const formElement = this.$el.querySelector('form');
      if (formElement && formElement.checkValidity()) {
        this.handleSubmit();
      } else if (formElement) {
        // 触发验证提示
        formElement.reportValidity();
      }
    }
  }
};
</script>

<style scoped>
/* 主题色适配 */
:root {
  --primary-color: v-bind(primaryColor);
}

/* 基础样式 */
.register-form-component {
  width: 100%;
  padding: 2rem 1rem;
  min-height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: v-bind(bgColor);
}

/* 渐变背景 */
.register-form-component:has([background-type="gradient"]) {
  background: linear-gradient(135deg, v-bind(bgColor), v-bind(bgColor2));
}

.register-form-wrapper {
  width: 100%;
  max-width: 500px;
}

/* 表单样式 */
.register-form {
  max-width: 450px;
  width: 100%;
  background-color: white;
  border-radius: calc(v-bind(formRadius) * 1px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  margin: 0 auto;
}

/* 标题样式 */
.section-title {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  color: v-bind(titleColor);
}

.section-subtitle {
  font-size: 1rem;
  line-height: 1.6;
  color: v-bind(subtitleColor);
}

/* 表单项样式 */
.form-group {
  margin-bottom: 1.5rem;
}

.form-label {
  display: block;
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: v-bind(labelColor);
}

.form-input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  color: #1f2937;
  background-color: white;
  transition: all 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
}

.form-input.error {
  border-color: #ef4444;
}

/* 验证码按钮 */
.code-button {
  padding: 0.75rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
  background-color: rgba(22, 93, 255, 0.1);
  color: var(--primary-color);
  border: 1px solid transparent;
}

.code-button:hover:not(.disabled) {
  background-color: var(--primary-color);
  color: white;
}

.code-button.disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 切换密码按钮 */
.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(107, 114, 128, 0.7);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
}

.toggle-password:hover {
  color: var(--primary-color);
}

/* 错误消息 */
.error-message {
  color: #ef4444;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

/* 用户协议复选框 */
.terms-checkbox {
  width: 1rem;
  height: 1rem;
  margin-top: 0.25rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
}

.terms-checkbox.error {
  border-color: #ef4444;
}

/* 提交按钮 */
.submit-button {
  width: 100%;
  padding: 0.75rem;
  border-radius: 8px;
  font-weight: 600;
  font-size: 1rem;
  color: white;
  background-color: var(--primary-color);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 14px 0 rgba(22, 93, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-button:hover:not(:disabled) {
  box-shadow: 0 6px 16px 0 rgba(22, 93, 255, 0.4);
  transform: translateY(-1px);
}

.submit-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 第三方登录按钮 */
.social-button {
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: none;
}

.social-wechat {
  background-color: rgba(7, 193, 96, 0.1);
  color: #07c160;
}

.social-wechat:hover {
  background-color: #07c160;
  color: white;
}

.social-qq {
  background-color: rgba(18, 183, 245, 0.1);
  color: #12b7f5;
}

.social-qq:hover {
  background-color: #12b7f5;
  color: white;
}

.social-github {
  background-color: rgba(36, 41, 46, 0.1);
  color: #24292e;
}

.social-github:hover {
  background-color: #24292e;
  color: white;
}

/* 链接样式 */
.primary-link {
  color: var(--primary-color);
  transition: color 0.2s ease;
}

.primary-link:hover {
  color: #0e4ab8;
  text-decoration: underline;
}

/* 状态消息 */
.status-message {
  margin-top: 1rem;
  padding: 0.75rem 1rem;
  border-radius: 8px;
  font-size: 0.875rem;
}

.status-message.success {
  background-color: #d1fae5;
  color: #065f46;
}

.status-message.error {
  background-color: #fee2e2;
  color: #991b1b;
}

/* 加载动画 */
.fa-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 640px) {
  .register-form {
    padding: 1.5rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
  
  .section-title {
    font-size: 1.75rem;
  }
}
</style>